<?php
/**
 * Created by PhpStorm.
 * User: UsWork-02
 * Date: 2021/8/2
 * Time: 15:00
 */

namespace app\api\controller;
use app\common\controller\Mqtt;
use think\Config;
use think\Controller;
use think\Db;
use think\Exception;

class Stakeoperation extends Controller
{
    static $uniacid = 1;

    //刷卡操作
    public function payCard($username,$division){
        $stakeWhere['deviceUuid'] = $username;
        $data['contetn'] = "刷卡";
        $data['username'] = empty($body[1])?'username':$body[1];
        $data['topic'] = empty($body[2])?'topic':$body[2];
        $data['timestamp'] = empty($body[3])?'timestamp':$body[3];
        $data['node'] = empty($body[4])?'node':$body[4];
        $data['clientid'] = empty($body[5])?'clientid':$body[5];
        $data['addtime'] = date("Y-m-d H:i:s");
        if(!empty($division[2])){
            $data['instructions'] = empty($instructions[$division[2]])?"其他指令":$instructions[$division[2]];
        }
        $instructions = '';
        $username = $data['username'];
        $Stakeoperation = new Stakeoperation();
        $Stakeoperation->handle("test",$data);  //记录操作命令行
    }


    //服务器停止单端口
    public function stopPort($username,$division,$state){
        $port = hexdec($division[3]);  //端口号
        $stakeWhere['deviceUuid'] = $username;
        $detail = $this->public_select("device_stake",$stakeWhere)->find();
        $config = $this->appointConfig($detail['uniacid']);
        $stakeWhere['positionUuid'] = $port;
        $addData['state'] = $state;
        Db::connect($config)->name("device_stake_port")->where($stakeWhere)->update($addData);
    }

    //更新端口工作状态(设备启动单端口)
    public function statePort($username,$division){
        $port = hexdec($division[3]);  //端口号
        $status = hexdec($division[4]);  //状态
        $status = empty($status)?1:2;
        $stakeWhere['deviceUuid'] = $username;
        $detail = $this->public_select("device_stake",$stakeWhere)->find();
        $config = $this->appointConfig($detail['uniacid']);
        $stakeWhere['positionUuid'] = $port;
        $addData['state'] = $status;
        Db::connect($config)->name("device_stake_port")->where($stakeWhere)->update($addData);
    }


    //更新设备端口信息
    public function cumulativeAd($username,$division){
        $port = hexdec($division[3]);  //端口号
        $value = hexdec($division[4].$division[5]);  //类型  剩余时间or剩余电量
        $stakeWhere['deviceUuid'] = $username;
        $detail = $this->public_select("device_stake",$stakeWhere)->find();
        $config = $this->appointConfig($detail['uniacid']);
        $stakeWhere['positionUuid'] = $port;
        Db::connect($config)->name("device_stake_port")->where($stakeWhere)->setInc("cumulativeAd",$value);
    }

    //更新设备端口信息
    public function updatePort($username,$division){
        $type = hexdec($division[3]);  //类型  0剩余时间  1剩余电量
        $port = hexdec($division[4]);  //端口号
        $value = hexdec($division[5].$division[6]);  //类型  剩余时间or剩余电量
        $power = hexdec($division[7].$division[8]);
        $stakeWhere['deviceUuid'] = $username;
        $detail = $this->public_select("device_stake",$stakeWhere)->find();

        switch ($type){
            case 0:
                $addData['surplusTime'] = $value;
                break;
            case 1:
                $addData['powerAd'] = $value;
                break;
        }
        $addData['power'] = $power;
        $config = $this->appointConfig($detail['uniacid']);
        $stakeWhere['positionUuid'] = $port;
        Db::connect($config)->name("device_stake_port")->where($stakeWhere)->update($addData);
    }

    //更新设备信息
    public function updateStake($username,$division,$field){
        $stakeWhere['deviceUuid'] = $username;
        $detail = $this->public_select("device_stake",$stakeWhere)->find();

        switch ($field){
            case "temperature":
                $temperature = hexdec($division[3]);  //实时的机箱温度
                $controlState =  hexdec($division[4]);  //报警标识
                $addData[$field] = $temperature;
                $addData["controlState"] = $controlState;
                $upData[$field] = $temperature;
                $upData["controlState"] = $controlState;
                break;
            case "totalElectric":
                $temperature = hexdec($division[3].$division[4].$division[5].$division[6]);  //实时的机箱温度
                $addData[$field] = $temperature;
                $upData[$field] = $temperature;
                break;
            case "temperatureValue":
                $temperature = hexdec($division[3]);  //实时的机箱温度
                $addData['temperature'] = $temperature;
                $upData['temperature'] = $temperature;
                break;
            case "power":
                $temperature = hexdec($division[3].$division[4]);  //设备端实时总功率
                $addData[$field] = $temperature;
                $upData[$field] = $temperature;
                break;
        }

        if(!empty($detail)){
            $addData['id'] = $detail['id'];
            $this->handle("device_stake",$addData);  //更新主表信息
            if($detail['uniacid']!=1){
                //更新分表
                $config = $this->appointConfig($detail['uniacid']);
                $uniacidWhere['deviceUuid'] = $username;
                $uniacidWhere['uniacid'] = $detail['uniacid'];
                $stakeId = Db::connect($config)->name("device_stake")->where($uniacidWhere)->update($upData);
            }
        }
    }


    //更新设备IMEI
    public function updateImei($username,$data,$field){
        $stakeWhere['deviceUuid'] = $username;
        $detail = $this->public_select("device_stake",$stakeWhere)->find();
        switch ($field){
            case "IMEI":
                $data = hex2bin($data);
                break;
            case "signal":
                $data = hexdec($data);
                break;
            case "power":  //总功率异常
                $upData['deviceState'] = 4;
                $addData['deviceState'] = 4;
                //待完善

                break;
        }
        if(!empty($detail)){
            $addData['id'] = $detail['id'];
            $addData[$field] = $data;
            $this->handle("device_stake",$addData);  //更新主表信息
            if($detail['uniacid']!=1){
                $upData[$field] = $data;
                //更新分表
                $config = $this->appointConfig($detail['uniacid']);
                $uniacidWhere['deviceUuid'] = $username;
                $uniacidWhere['uniacid'] = $detail['uniacid'];
                $stakeId = Db::connect($config)->name("device_stake")->where($uniacidWhere)->update($upData);
            }
        }
        return true;
    }

    //同步设备配置
    public function synchroConfig($username,$division){
        $stakeWhere['deviceUuid'] = $username;
        $detail = $this->public_select("device_stake",$stakeWhere)->find();
        if(!empty($detail)){
            //更新分表
            $config = $this->appointConfig($detail['uniacid']);
            $uniacidWhere['deviceUuid'] = $username;
            $uniacidWhere['uniacid'] = $detail['uniacid'];
            $id = Db::connect($config)->name("device_stake_config")->where($uniacidWhere)->value("id");

            $addDate['mode'] = hexdec($division[3]);
            $addDate['errorTime'] = hexdec($division[4]);
            $addDate['totalPower'] = hexdec($division[5].$division[6]);
            $addDate['maxPower'] = hexdec($division[7].$division[8]);
            $addDate['minPower'] = hexdec($division[9]);
            $addDate['astrictMaxPower'] = hexdec($division[10].$division[11]);
            $addDate['astrictMinPower'] = hexdec($division[12]);
            $addDate['lowWarm'] = hexdec($division[13]);
            $addDate['highWarm'] = hexdec($division[14]);
            $addDate['ultraWarm'] = hexdec($division[15]);
            $addDate['heartbeat'] = hexdec($division[16].$division[17]);
            $addDate['portCount'] = hexdec($division[18]);
            if(empty($id)){
                $addDate['deviceUuid'] = $username;
                $addDate['uniacid'] = $detail['uniacid'];
                $addDate['status'] = 2;
                Db::connect($config)->name("device_stake_config")->where($uniacidWhere)->insert($addDate);
            }else{
                $addDate['status'] = 2;
                Db::connect($config)->name("device_stake_config")->where($uniacidWhere)->update($addDate);
            }
        }
    }


    //更新设备配置
    public function updateConfig($username,$data){
        $stakeWhere['deviceUuid'] = $username;
        $detail = $this->public_select("device_stake",$stakeWhere)->find();
        if(!empty($detail)){
            $addData['id'] = $detail['id'];
            $addData["status"] = hexdec($data);
            //更新分表
            $config = $this->appointConfig($detail['uniacid']);
            $uniacidWhere['deviceUuid'] = $username;
            $uniacidWhere['uniacid'] = $detail['uniacid'];
            Db::connect($config)->name("device_stake_config")->where($uniacidWhere)->update($addData);
        }
    }



    //记录设备心跳
    public function heartbeat($username){
        $stakeWhere['deviceUuid'] = $username;
        $id = $this->public_select("device_stake",$stakeWhere)->value("id");
        if(!empty($id)){
            $addData['id'] = $id;
        }else{
            $addData['uniacid'] = self::$uniacid;
            $addData['number'] = $username;
            $addData['deviceUuid'] = $username;
            $addData['deviceName'] = $username;
            $addData['addtime'] = time();
        }
        $addData['heartbeat'] = time();
        $this->handle("device_stake",$addData);
        return true;
    }

    //查询指定config配置
    public function appointConfig($id){
        //查询平台配置
        $config= $this->public_select("config_platform",['id'=>$id],"id,hostname,database,username,password,hostport")->find();
        if(!empty($config)){
            $config['type'] = 'mysql';
            $config['prefix'] = 'us_';
        }
        return empty($config)?null:$config;
    }


    //获取config配置
    public function selconfig(){
        if(!empty(self::$uniacid)){
            //查询平台配置
            $config= $this->public_select("config_platform",['uniacid'=>self::$uniacid],"id,hostname,database,username,password,hostport")->find();
            if(!empty($config)){
                $config['type'] = 'mysql';
                $config['prefix'] = 'us_';
            }
        }
        return empty($config)?null:$config;
    }

    /**
     * 查询条件
     * @author zhixuedong
     * @date 2021/1/20/020
     */
    public function public_select($table,$where,$field=null,$start=0,$limit=0){
        $tableArray = $this->coreTable();
        if(!in_array($table,$tableArray)){
            $config = $this->selconfig();
        }else{
            $config = null;
        }

        $data = Db::connect($config)->name($table)->where($where);
        if($limit!=0){
            $data = $data->limit($start,$limit);
        }
        if(!empty($field)){
            $data = $data->field($field);
        }
        return $data;
    }

    public function handle($table,$data,$type=0){
        $tableArray = $this->coreTable();
        if(!in_array($table,$tableArray)){
            $config = $this->selconfig();
        }else{
            $config = [];
        }
        if(empty($data['id'])){
            $id = Db::connect($config)->name($table)->insertGetId($data,true);
        }else{
            $id = $data['id'];
            Db::connect($config)->name($table)->where(['id'=>$id])->update($data);
        }
        return $id;
    }

    /*
     *核心表
     */
    public function coreTable(){
        $tableArray = ['privilege','config_platform','config_attribute','admin_region','config'];
        return $tableArray;
    }
}